<template>
  <!-- 后台用户管理 -->
  <main class="w-full h-full dark:bg-black p-4">
    <use-table
      :searchSelectOption="searchSelectOption"
      :allData="allData"
      :columns="columns"
      :personalized="true"
      :loading="loading"
      :total="total"
      v-model:selectedRowKey="selectedRowKey"
      @modifyUserData="openModifyUserDataForm"
      @deleteSelectUser="deleteSelectUser"
    >
      <template #function>
        <a-tooltip placement="bottom">
          <template #title>
            <span>添加用户</span>
          </template>
          <div class="cursor-pointer text-lg text-blue-500 mr-2" @click="openAddUserForm">
            <plus-circle-outlined />
          </div>
        </a-tooltip>
        <a-tooltip placement="bottom">
          <template #title>
            <span>删除选中用户</span>
          </template>
          <div class="cursor-pointer text-lg text-red-500 mr-2" @click="deleteSelectUser">
            <close-circle-outlined />
          </div>
        </a-tooltip>
      </template>
      <template #title> 用户管理 </template>
    </use-table>
    <modify-form
      @handleOk="modifyUserInfoOk"
      v-model:visible="visible"
      :modalTitleText="modalTitleText"
    >
      <template #container>
        <div class="flex items-center">
          <span class="w-14"> 姓名： </span>
          <a-input v-model:value="modifyUserInfoFrom.name" placeholder="修改用户姓名" />
        </div>
        <div class="flex mt-3 items-center">
          <span class="w-14"> 密码： </span>
          <a-input v-model:value="modifyUserInfoFrom.password" placeholder="修改用户姓名" />
        </div>
        <div class="mt-3 flex items-center">
          <span class="w-12"> 权限： </span>
          <a-checkbox-group
            v-model:value="modifyUserInfoFrom.role"
            name="checkboxgroup"
            :options="options"
          />
        </div>
        <div class="mt-3">
          <span>状态：</span>
          <a-switch
            :checked="modifyUserInfoFrom.status === 0 ? false : true"
            checked-children="启用"
            un-checked-children="禁用"
            @click="handleModifySwitchChange"
          />
        </div>
      </template>
    </modify-form>
    <modify-form
      @handleOk="completeAddUser"
      v-model:visible="addUserModalVisible"
      modalTitleText="添加用户"
    >
      <template #container>
        <div class="flex items-center">
          <span class="w-14"> 姓名： </span>
          <a-input v-model:value="addUserForm.username" placeholder="输入用户姓名" />
        </div>
        <div class="flex mt-3 items-center">
          <span class="w-14"> 密码： </span>
          <a-input v-model:value="addUserForm.password" placeholder="输入用户密码" />
        </div>
        <div class="mt-3">
          <span> 权限： </span>
          <a-checkbox-group
            v-model:value="addUserForm.role"
            name="checkboxgroup"
            :options="options"
          />
        </div>
        <div class="mt-3">
          <span>状态：</span>
          <a-switch
            :checked="addUserForm.status === 0 ? false : true"
            checked-children="启用"
            un-checked-children="禁用"
            @click="addUserForm.status === 0 ? (addUserForm.status = 1) : (addUserForm.status = 0)"
          />
        </div>
      </template>
    </modify-form>
  </main>
</template>

<script setup lang="ts">
  import { AdminUser } from '@/utils/interface';
  import {
    getAllAdminUser,
    deleteAdminUser,
    modifyAdminUserInfo,
    addAdminUser,
  } from '@/api/adminUser';
  import { message } from 'ant-design-vue';
  import { CloseCircleOutlined, PlusCircleOutlined } from '@ant-design/icons-vue';

  const searchSelectOption: { value: string; label: string }[] = [
    {
      value: 'username',
      label: '姓名',
    },
  ];
  // 表头
  const columns = [
    {
      title: '权限',
      dataIndex: 'role',
      align: 'center',
      width: 160,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      align: 'center',
      width: 120,
    },
    {
      title: '密码',
      dataIndex: 'password',
      align: 'center',
      width: 90,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 80,
    },
    {
      title: '最后登录时间',
      dataIndex: 'login_time',
      align: 'center',
      width: 160,
      sorter: (a, b) => a.login_time - b.login_time,
    },
    {
      title: '添加时间',
      dataIndex: 'add_time',
      align: 'center',
      width: 160,
      sorter: (a, b) => a.add_time - b.add_time,
    },
    {
      title: '操作',
      align: 'center',
      width: 80,
      dataIndex: 'operation',
    },
  ];
  // 是否加载
  let loading = ref(true);
  let total = ref(0);
  let allData = ref<AdminUser[]>([]);
  // 勾选的数据的key
  let selectedRowKey = ref<number[] | string[]>([]);
  async function getAllAdminUserData() {
    const res = await getAllAdminUser();
    allData.value = res.data;
    total.value = allData.value.length;
    loading.value = false;
  }
  getAllAdminUserData();
  // 删除选中用户
  const deleteSelectUser = async (key) => {
    const selectKey = Array.isArray(key) ? key : selectedRowKey.value;
    if (!selectKey) {
      message.warning('请选择要删除的用户');
      return;
    }
    loading.value = true;
    const res = await deleteAdminUser(selectKey);
    if (res.status === 200) {
      message.success('删除成功');
    }
    getAllAdminUserData();
    loading.value = false;
  };
  const options = [
    { label: '超级管理员', value: 1 },
    { label: '学生管理员', value: 2 },
    { label: '考试管理员', value: 3 },
  ];
  let addUserForm = ref({
    username: '',
    password: '',
    role: [],
    status: 0,
  });
  let addUserModalVisible = ref(false);
  // 打开添加用户弹窗
  const openAddUserForm = () => {
    addUserModalVisible.value = true;
  };
  // 完成添加用户
  const completeAddUser = async () => {
    if (
      addUserForm.value.username === '' ||
      addUserForm.value.password === '' ||
      !addUserForm.value.role
    ) {
      message.warning('请输入完整的信息');
      return;
    }
    const res = await addAdminUser({
      username: addUserForm.value.username.trim(),
      password: addUserForm.value.password.trim(),
      role: addUserForm.value.role,
      status: addUserForm.value.status,
    });
    if (res.status === 200) {
      message.success('添加成功');
      loading.value = true;
      await getAllAdminUserData();
      addUserForm.value = {
        username: '',
        password: '',
        role: [],
        status: 0,
      };
      addUserModalVisible.value = false;
      loading.value = false;
    }
  };
  // 修改用户信息框显示
  let visible = ref<boolean>(false);
  // 修改用户信息
  const modifyUserInfoFrom = reactive<{
    name: string;
    password: string;
    role: number[] | string[];
    status: number;
    key: number;
  }>({
    name: '',
    password: '',
    role: [-1],
    status: -1,
    key: -1,
  });
  let modalTitleText = ref('修改用户信息');
  // 点击修改按钮
  const openModifyUserDataForm = (key: number) => {
    const clickUser = allData.value.find((item: any) => item.key === key) as any;

    if (clickUser !== undefined) {
      modalTitleText.value = `修改 ${clickUser.username} 的信息`;
      modifyUserInfoFrom.name = clickUser.username;
      modifyUserInfoFrom.role = [...new Set(clickUser.role.map((item) => item.key))] as number[];
      modifyUserInfoFrom.password = clickUser.password;
      modifyUserInfoFrom.status = clickUser.status;
      modifyUserInfoFrom.key = clickUser.key;
      visible.value = true;
    } else message.error('发生错误');
  };
  // 在弹出框修改用户状态
  const handleModifySwitchChange = () => {
    modifyUserInfoFrom.status = modifyUserInfoFrom.status === 0 ? 1 : 0;
  };

  // 点击ok
  const modifyUserInfoOk = async () => {
    const { name: username, password, status, role: roles, key } = modifyUserInfoFrom;
    if (username === '' || password === '') {
      message.error('请填写完整信息');
      return;
    }
    // 整合数据
    const data = {
      id: key,
      username,
      password,
      status,
      roles,
    };
    const res = (await modifyAdminUserInfo(data)) as any;
    loading.value = true;
    visible.value = false;
    if (res.status === 200) {
      message.success(res.msg);
      getAllAdminUserData();
    }
    loading.value = false;
  };
</script>
